package com.example.SocialApplication.service;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Base64;

import com.example.SocialApplication.constants.URLs;
import com.example.SocialApplication.db.entity.ImageEntity;
import com.example.SocialApplication.db.entity.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by differ on 08.09.13.
 */
public class CallServiceGetImageById extends AsyncTask<Void, Void, Void> implements URLs {

    private Context mContext;
    private List<String> mList;

    public CallServiceGetImageById(Context context, List<String> list) {
        mContext = context;
        mList = list;
    }

    @Override
    protected Void doInBackground(Void... voids) {
        for (String item : mList) {                   /// todo NPE on first start
            String url = GET_IMAGE_BY_ID_URL.replace("${id}", item);
            String result = "";

            try {
                result = HttpServices.callHttpGetRequest(url);
            } catch (IOException e) {
                e.printStackTrace();
            }

            ImageEntity image = null;
            if (!result.equals("")) {
                Gson gson = new Gson();
                image = gson.fromJson(result, ImageEntity.class);
            }

            if (image != null) {
                String[] splitted = image.getImage().split("base64,");

                byte[] imageAsBytes = Base64.decode(splitted[0], Base64.DEFAULT);
                Bitmap bitmap = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);

                String pathToFolder = mContext.getExternalCacheDir().getAbsolutePath()
                        + File.separator
                        + "images"
                        + File.separator;

                String fileName = File.separator + item + ".png";
                String path = pathToFolder + fileName;

                File f = new File(path);
                if (!f.exists()) {
                    new File(pathToFolder).mkdirs();
                    try {
                        f.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(f);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                System.gc();
            }
        }

        return null;
    }
}
